//
//  UpdateChecker.m
//  chameleon
//
//  Created by Justin Yip on 6/17/14.
//
//

#import "UpdateChecker.h"
#import <ReactiveCocoa.h>
#import <AFNetworking.h>
#import "ZillaClient.h"

@implementation UpdateChecker

+ (void)check
{
    NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSInteger currentBuild = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] integerValue];
    
    [[ZillaClient getLastestAppVersion] subscribeNext:^(id x) {
        NSNumber *build = x[@"build"];
        NSString *version = x[@"version"];
//        NSString *packageID = x[@"bundle"];
        NSString *plistID = x[@"plist"];
        NSString *repleaseNote = x[@"releaseNote"];
        
        if (build && build.integerValue > currentBuild) {
            
            NSString *message = [NSString stringWithFormat:@"当前版本:%@\n最新版本:%@\n版本说明:\n%@",
                                 currentVersion, version, repleaseNote];
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:[ NSString stringWithFormat:@"%@平台版本更新",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"] ] message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
            [av show];
            
            [av.rac_buttonClickedSignal subscribeNext:^(NSNumber *indexNumber) {
                if ([indexNumber intValue] == 1) {
                    NSURL *url = [NSURL URLWithString:[ZillaClient itmsURLStringForAppPlistFileID:plistID]];
                    [[UIApplication sharedApplication] openURL:url];
                }
            }];
        } else {
            NSLog(@"没有更新");
        }
        
    } error:^(NSError *error) {
        NSLog(@"检查更新失败:%@", error);
    }];
}

@end
